﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ExcelRefresh.Excel;

namespace RefreshExcel
{
    class Program
    {
        static void Main(string[] args)
        {
            string backupPath = null;
            string saveToPath = null;
            string sourcePath = null;

            Console.WriteLine();
            Console.WriteLine("RefreshExcel - Refreshes data in an Excel workbook");
            Console.WriteLine("==================================================");
            Console.WriteLine();
            try
            {
                if (args.Length == 0 || string.IsNullOrEmpty(args[0]))
                    throw new Exception("An Excel input file is required");

                if (File.Exists(args[0]))
                    sourcePath = args[0].Replace("\"","");
                else
                    throw new Exception("File not found: " + args[0]);

                for (int i = 1; i < args.Length; i++)
                {
                    var arg = args[i];
                    if(string.IsNullOrEmpty(arg))
                        continue;

                    if (arg[0] == '/')
                    {
                        if(arg.StartsWith("/S:"))
                            saveToPath = parseTargetPath(sourcePath, arg.Substring(3));
                        else if(arg.StartsWith("/B:"))
                            backupPath = parseTargetPath(sourcePath, arg.Substring(3));
                        else
                        switch (arg.Substring(1).ToUpperInvariant())
                        {
                            case "H":
                            case "?":
                                ShowHelp();
                                break;
                            default:
                                throw new Exception("Command not recognized: " + arg);
                        }
                    }
                    else
                        throw new Exception("Command not recognized: " + arg);
                }
            }
            catch(Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine();
                ShowHelp();
                return;
            }

            Console.WriteLine("Refreshing {0}" , sourcePath);
            try
            {
                ExcelUtilities.RefreshWorkbook(sourcePath, saveToPath ?? sourcePath, backupPath);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: {0}", ex.Message);
                Console.Error.WriteLine("Error: {0}", ex.Message);
                throw;
            }
        }

        private static string parseTargetPath(string sourceFile, string targetPath)
        {
            var extension = Path.GetExtension(sourceFile) ?? ".xlsx";
            var filename = Path.GetFileNameWithoutExtension(sourceFile);
            var rootPath = Path.GetDirectoryName(sourceFile);

            if(targetPath.StartsWith(@"""") && targetPath.EndsWith(@""""))
                targetPath = targetPath.Substring(1, targetPath.Length - 2);

            return string.Format(targetPath, rootPath, filename, extension, DateTime.Now).Replace(@"\\",@"\");
        }

        private static void ShowHelp()
        {
            Console.WriteLine("Syntax:     RefreshExcel filename.xlsx [options]");
            Console.WriteLine("Options:");
            Console.WriteLine("  /? or /h     : Show help");
            Console.WriteLine("  /S:path      : Save file to path.");
            Console.WriteLine("  /B:path      : Create a backup copy to path.");
            Console.WriteLine();
            Console.WriteLine("Format expressions available for path:");
            Console.WriteLine("  {0}          : Input folder path (exludes filename)");
            Console.WriteLine("  {1}          : Input file name (without extension)");
            Console.WriteLine("  {2}          : Input file extension");
            Console.WriteLine("  {3}          : Current Date Time.");
            Console.WriteLine();
            Console.WriteLine(" Usage Examples:");
            Console.WriteLine();
            Console.WriteLine(@"Open, refresh and save Sheet.xlsx:");
            Console.WriteLine(@"       RefreshExcel ""C:\Sheet.xksx""");
            Console.WriteLine();
            Console.WriteLine(@"Refresh Sheet.xlsx and save to another folder:");
            Console.WriteLine(@"       RefreshExcel ""C:\Sheet.xksx"" /S:""C:\Refreshed\Sheet.xlsx""");
            Console.WriteLine();
            Console.WriteLine(@"Refresh Sheet.xlsx and save to a Sheet20131201.xlsx  (if today were 2013-12-01)  :");
            Console.WriteLine(@"       RefreshExcel ""C:\Sheet.xksx"" /S:""C:\Sheet{3:yyyyMMdd}.xlsx""");
            Console.WriteLine();
            Console.WriteLine(@"Refresh Sheet.xlsx and save an archive to a C:\Sheet\Archive 20131201.xlsx  (if today were 2013-12-01)  :");
            Console.WriteLine(@"       RefreshExcel ""C:\Sheet.xksx"" /B:""{0}\{1}\Archive{3:yyyyMMdd}.xlsx""");
        }

       


        


    }
}
